/**
 * 插件管理器组件
 * 
 * 提供插件的动态管理和配置界面
 * 支持插件的启用/禁用、配置修改等功能
 */

import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Switch, 
  Button, 
  Modal, 
  Form, 
  Input, 
  Select, 
  Tag, 
  Space, 
  Tooltip,
  message,
  Descriptions,
  Divider
} from 'antd';
import {
  SettingOutlined,
  InfoCircleOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import pluginInitializer from '../../plugins/PluginInitializer';

const { Option } = Select;

const PluginManager = () => {
  const [graphTypePlugins, setGraphTypePlugins] = useState([]);
  const [layoutPlugins, setLayoutPlugins] = useState([]);
  const [compatibilityMatrix, setCompatibilityMatrix] = useState([]);
  const [selectedPlugin, setSelectedPlugin] = useState(null);
  const [configModalVisible, setConfigModalVisible] = useState(false);
  const [infoModalVisible, setInfoModalVisible] = useState(false);
  const [loading, setLoading] = useState(true);
  const [form] = Form.useForm();

  // 加载插件数据
  useEffect(() => {
    loadPluginData();
  }, []);

  const loadPluginData = async () => {
    try {
      setLoading(true);
      
      // 确保插件系统已初始化
      await pluginInitializer.initialize();
      
      const registry = pluginInitializer.getRegistry();
      
      // 获取图谱类型插件
      const graphTypes = registry.getRegisteredGraphTypes();
      const graphTypeData = graphTypes.map(type => {
        const plugin = registry.getGraphTypePlugin(type);
        return {
          key: type,
          type,
          name: plugin.name,
          version: plugin.version,
          description: plugin.description,
          supportedLayouts: plugin.supportedLayouts || [],
          enabled: true, // 默认启用
          plugin
        };
      });

      // 获取布局插件
      const layouts = registry.getRegisteredLayouts();
      const layoutData = layouts.map(layout => {
        const plugin = registry.getLayoutPlugin(layout);
        return {
          key: layout,
          layout,
          name: plugin.name,
          version: plugin.version,
          description: plugin.description,
          supportedGraphTypes: plugin.supportedGraphTypes || [],
          enabled: true, // 默认启用
          plugin
        };
      });

      // 生成兼容性矩阵
      const matrix = [];
      graphTypes.forEach(graphType => {
        layouts.forEach(layout => {
          const isCompatible = registry.isCompatible(graphType, layout);
          matrix.push({
            key: `${graphType}-${layout}`,
            graphType,
            layout,
            compatible: isCompatible,
            combination: registry.getCombinationPlugin(graphType, layout)
          });
        });
      });

      setGraphTypePlugins(graphTypeData);
      setLayoutPlugins(layoutData);
      setCompatibilityMatrix(matrix);
      
    } catch (error) {
      console.error('加载插件数据失败:', error);
      message.error('加载插件数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 图谱类型插件表格列定义
  const graphTypeColumns = [
    {
      title: '插件名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          <strong>{text}</strong>
          <Tag color="blue">{record.type}</Tag>
        </Space>
      ),
    },
    {
      title: '版本',
      dataIndex: 'version',
      key: 'version',
      width: 100,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '支持的布局',
      dataIndex: 'supportedLayouts',
      key: 'supportedLayouts',
      render: (layouts) => (
        <Space wrap>
          {layouts.map(layout => (
            <Tag key={layout} color="green" size="small">
              {layout}
            </Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      key: 'enabled',
      width: 80,
      render: (enabled, record) => (
        <Switch
          checked={enabled}
          onChange={(checked) => handlePluginToggle('graph', record.type, checked)}
          size="small"
        />
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 120,
      render: (_, record) => (
        <Space>
          <Tooltip title="查看详情">
            <Button
              type="text"
              icon={<InfoCircleOutlined />}
              onClick={() => handleShowInfo(record)}
              size="small"
            />
          </Tooltip>
          <Tooltip title="配置">
            <Button
              type="text"
              icon={<SettingOutlined />}
              onClick={() => handleShowConfig(record)}
              size="small"
            />
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 布局插件表格列定义
  const layoutColumns = [
    {
      title: '插件名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          <strong>{text}</strong>
          <Tag color="orange">{record.layout}</Tag>
        </Space>
      ),
    },
    {
      title: '版本',
      dataIndex: 'version',
      key: 'version',
      width: 100,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '支持的图谱类型',
      dataIndex: 'supportedGraphTypes',
      key: 'supportedGraphTypes',
      render: (types) => (
        <Space wrap>
          {types.length === 0 ? (
            <Tag color="default" size="small">全部</Tag>
          ) : (
            types.map(type => (
              <Tag key={type} color="purple" size="small">
                {type}
              </Tag>
            ))
          )}
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      key: 'enabled',
      width: 80,
      render: (enabled, record) => (
        <Switch
          checked={enabled}
          onChange={(checked) => handlePluginToggle('layout', record.layout, checked)}
          size="small"
        />
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 120,
      render: (_, record) => (
        <Space>
          <Tooltip title="查看详情">
            <Button
              type="text"
              icon={<InfoCircleOutlined />}
              onClick={() => handleShowInfo(record)}
              size="small"
            />
          </Tooltip>
          <Tooltip title="配置">
            <Button
              type="text"
              icon={<SettingOutlined />}
              onClick={() => handleShowConfig(record)}
              size="small"
            />
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 兼容性矩阵表格列定义
  const compatibilityColumns = [
    {
      title: '图谱类型',
      dataIndex: 'graphType',
      key: 'graphType',
      render: (text) => <Tag color="blue">{text}</Tag>,
    },
    {
      title: '布局类型',
      dataIndex: 'layout',
      key: 'layout',
      render: (text) => <Tag color="orange">{text}</Tag>,
    },
    {
      title: '兼容性',
      dataIndex: 'compatible',
      key: 'compatible',
      render: (compatible) => (
        <Space>
          {compatible ? (
            <CheckCircleOutlined style={{ color: '#52c41a' }} />
          ) : (
            <ExclamationCircleOutlined style={{ color: '#ff4d4f' }} />
          )}
          <span style={{ color: compatible ? '#52c41a' : '#ff4d4f' }}>
            {compatible ? '兼容' : '不兼容'}
          </span>
        </Space>
      ),
    },
    {
      title: '组合状态',
      key: 'combination',
      render: (_, record) => (
        record.combination ? (
          <Tag color="success">已创建</Tag>
        ) : (
          <Tag color="default">未创建</Tag>
        )
      ),
    },
  ];

  // 处理插件启用/禁用
  const handlePluginToggle = (type, name, enabled) => {
    if (type === 'graph') {
      setGraphTypePlugins(prev => 
        prev.map(plugin => 
          plugin.type === name ? { ...plugin, enabled } : plugin
        )
      );
    } else {
      setLayoutPlugins(prev => 
        prev.map(plugin => 
          plugin.layout === name ? { ...plugin, enabled } : plugin
        )
      );
    }
    
    message.success(`插件 ${name} 已${enabled ? '启用' : '禁用'}`);
  };

  // 显示插件详情
  const handleShowInfo = (plugin) => {
    setSelectedPlugin(plugin);
    setInfoModalVisible(true);
  };

  // 显示插件配置
  const handleShowConfig = (plugin) => {
    setSelectedPlugin(plugin);
    form.setFieldsValue(plugin.plugin.config || {});
    setConfigModalVisible(true);
  };

  // 保存插件配置
  const handleSaveConfig = async () => {
    try {
      const values = await form.validateFields();
      // 这里可以实现配置保存逻辑
      console.log('保存插件配置:', selectedPlugin, values);
      message.success('配置保存成功');
      setConfigModalVisible(false);
    } catch (error) {
      console.error('保存配置失败:', error);
    }
  };

  // 刷新插件数据
  const handleRefresh = () => {
    loadPluginData();
    message.success('插件数据已刷新');
  };

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h2>插件管理器</h2>
        <Button 
          type="primary" 
          icon={<ReloadOutlined />} 
          onClick={handleRefresh}
          loading={loading}
        >
          刷新
        </Button>
      </div>

      {/* 图谱类型插件 */}
      <Card title="图谱类型插件" style={{ marginBottom: '24px' }}>
        <Table
          columns={graphTypeColumns}
          dataSource={graphTypePlugins}
          loading={loading}
          pagination={false}
          size="small"
        />
      </Card>

      {/* 布局插件 */}
      <Card title="布局插件" style={{ marginBottom: '24px' }}>
        <Table
          columns={layoutColumns}
          dataSource={layoutPlugins}
          loading={loading}
          pagination={false}
          size="small"
        />
      </Card>

      {/* 兼容性矩阵 */}
      <Card title="插件兼容性矩阵">
        <Table
          columns={compatibilityColumns}
          dataSource={compatibilityMatrix}
          loading={loading}
          pagination={{ pageSize: 10 }}
          size="small"
        />
      </Card>

      {/* 插件详情模态框 */}
      <Modal
        title="插件详情"
        open={infoModalVisible}
        onCancel={() => setInfoModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setInfoModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={600}
      >
        {selectedPlugin && (
          <Descriptions column={1} bordered size="small">
            <Descriptions.Item label="插件名称">{selectedPlugin.name}</Descriptions.Item>
            <Descriptions.Item label="版本">{selectedPlugin.version}</Descriptions.Item>
            <Descriptions.Item label="描述">{selectedPlugin.description}</Descriptions.Item>
            <Descriptions.Item label="类型">
              {selectedPlugin.type ? '图谱类型插件' : '布局插件'}
            </Descriptions.Item>
            {selectedPlugin.supportedLayouts && (
              <Descriptions.Item label="支持的布局">
                {selectedPlugin.supportedLayouts.join(', ')}
              </Descriptions.Item>
            )}
            {selectedPlugin.supportedGraphTypes && (
              <Descriptions.Item label="支持的图谱类型">
                {selectedPlugin.supportedGraphTypes.length === 0 
                  ? '全部' 
                  : selectedPlugin.supportedGraphTypes.join(', ')
                }
              </Descriptions.Item>
            )}
            <Descriptions.Item label="状态">
              {selectedPlugin.enabled ? (
                <Tag color="success">已启用</Tag>
              ) : (
                <Tag color="default">已禁用</Tag>
              )}
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>

      {/* 插件配置模态框 */}
      <Modal
        title="插件配置"
        open={configModalVisible}
        onOk={handleSaveConfig}
        onCancel={() => setConfigModalVisible(false)}
        width={800}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            label="配置说明"
            style={{ marginBottom: '16px' }}
          >
            <div style={{ 
              padding: '12px', 
              background: '#f6ffed', 
              border: '1px solid #b7eb8f',
              borderRadius: '6px',
              fontSize: '12px',
              color: '#666'
            }}>
              这里可以配置插件的各种参数，修改后将影响插件的行为和外观。
            </div>
          </Form.Item>
          
          {/* 这里可以根据不同插件动态生成配置表单 */}
          <Form.Item label="插件名称" name="name">
            <Input disabled />
          </Form.Item>
          
          <Form.Item label="动画持续时间" name={['animateCfg', 'duration']}>
            <Input type="number" placeholder="毫秒" />
          </Form.Item>
          
          <Form.Item label="动画缓动函数" name={['animateCfg', 'easing']}>
            <Select placeholder="选择缓动函数">
              <Option value="easeQuadOut">easeQuadOut</Option>
              <Option value="easeLinear">easeLinear</Option>
              <Option value="easeQuadIn">easeQuadIn</Option>
              <Option value="easeCubicOut">easeCubicOut</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default PluginManager;